package com.shuwang.jh_shop.ui.base

import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

import java.lang.reflect.Field

/**
 * 作者  Administrator
 * 时间  2016/10/10 14:12
 * 文件  oilapp
 * 描述  延迟加载的封装类
 */

open class BaseLazyFragment : Fragment() {
    protected var inflater: LayoutInflater? = null
    private var contentView: View? = null
    private var container: ViewGroup? = null
    var applicationContext: Context? = null
        private set

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        this.applicationContext = context
    }

    /**
     * onCreateView的生命周期是怎样的
     */
    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        this.inflater = inflater
        this.container = container
        if (savedInstanceState != null)
        // Fragment 重建
            onRestartInstance(savedInstanceState)
        onCreateView(savedInstanceState)//创建布局 初始化了contentView的值
        if (contentView == null) {
            contentView = super.onCreateView(inflater, container, savedInstanceState)
        }
        return contentView
    }

    protected fun onRestartInstance(savedInstanceState: Bundle?) {
    }


    protected open fun onCreateView(savedInstanceState: Bundle?) {}

    override fun onDestroyView() {
        super.onDestroyView()
        contentView = null
        container = null
        inflater = null
    }

    open fun setContentView(layoutResID: Int) {
        setContentView(inflater!!.inflate(layoutResID, container, false))
    }

    open fun setContentView(view: View) {
        contentView = view
    }

    fun getContentView(): View? {
        return contentView
    }

    fun findViewById(id: Int): View? {
            return contentView?.findViewById(id)
    }

    // http://stackoverflow.com/questions/15207305/getting-the-error-java-lang-illegalstateexception-activity-has-been-destroyed
    override fun onDetach() {
        super.onDetach()
        try {
            val childFragmentManager = Fragment::class.java.getDeclaredField("mChildFragmentManager")
            childFragmentManager.isAccessible = true
            childFragmentManager.set(this, null)

        } catch (e: NoSuchFieldException) {
            throw RuntimeException(e)
        } catch (e: IllegalAccessException) {
            throw RuntimeException(e)
        }

    }

}
